package com.pethospital.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class JwtUtil {

    @Value("${pet-hospital.jwt.secret}")
    private String secret;

    @Value("${pet-hospital.jwt.expire}")
    private long expire;

    /**
     * 生成JWT token
     */
    public String generateToken(Long userId, Integer userType) {
        log.info("开始生成Token，用户ID: {}, 用户类型: {}", userId, userType);
        
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);
        
        log.info("Token生成时间: {}, 过期时间: {}", nowDate, expireDate);

        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("userType", userType); // 1-普通用户，2-医护人员

        String token = Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
                
        log.info("Token生成成功: {}", token);
        return token;
    }

    /**
     * 解析JWT token
     */
    public Claims getClaimsByToken(String token) {
        log.info("开始解析Token: {}", token);
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
            
            log.info("Token解析成功，Claims: {}", claims);
            return claims;
        } catch (ExpiredJwtException e) {
            log.error("Token已过期: {}", token, e);
            return null;
        } catch (SignatureException e) {
            log.error("Token签名验证失败: {}", token, e);
            return null;
        } catch (Exception e) {
            log.error("Token解析异常: {}", token, e);
            return null;
        }
    }

    /**
     * 判断token是否过期
     */
    public boolean isTokenExpired(Claims claims) {
        try {
            Date expiration = claims.getExpiration();
            boolean isExpired = expiration.before(new Date());
            log.info("检查Token是否过期，过期时间: {}, 当前时间: {}, 是否过期: {}", 
                    expiration, new Date(), isExpired);
            return isExpired;
        } catch (Exception e) {
            log.error("检查Token过期状态异常", e);
            return true;
        }
    }
} 